<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- 按钮 -->
        <div class="box">
          <el-button @click="openAdd(1, 0)" type="primary" size="mini"
            >添加菜单</el-button
          >
        </div>
        <!-- 表格 -->
        <el-table :data="tableData" row-key="id">
          <el-table-column prop="name" label="菜单名称"> </el-table-column>
          <el-table-column prop="code" label="权限标识"> </el-table-column>
          <el-table-column prop="description" label="描述"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button
                @click="openAdd(2, row.id)"
                v-if="row.type === 1"
                type="text"
                >添加权限</el-button
              >
              <el-button type="text">查看api权限</el-button>
              <el-button @click="openEdit(row.id)" type="text">查看</el-button>
              <el-button @click="del(row.id)" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 查看&新增面板 -->
      <aded
        ref="aded"
        @updatedata="getAllPermission"
        :adedShow.sync="adedShow"
      ></aded>
    </div>
  </div>
</template>

<script>
import { getAllPermissionApi, delSysPermissionApi } from '@/api/permission'
import aded from './compoents/aded.vue'
export default {
  components: { aded },
  data () {
    return {
      tableData: [], //权限列表
      adedShow: false
    }
  },
  methods: {
    //得到所有权限数据
    async getAllPermission () {
      const res = await getAllPermissionApi()
      console.log('得到所有权限数据', res)
      this.tableData = this.turnData(res, '0')
    },
    // 将数据转换为树状态结构
    turnData (arr, str) {
      // return arr.forEach((item)=>{})  forEach也可以
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.turnData(arr, item.id)
          return true
        }
        return false
      })
    },
    //删除权限点
    async del (id) {
      try {
        await this.$confirm('是否删除当前权限', '警告')
        await delSysPermissionApi(id)
        this.getAllPermission()
        this.$message.success('删除成功')
      } catch {
        // this.$message.error(err.message)
        console.log('取消')
      }
    },
    // 查看
    openEdit (id) {
      this.adedShow = true
      //根据id得到编辑面板中的权限数据
      this.$refs.aded.getPermissionById(id)
    },
    //打开新增面板
    openAdd (type, pid) {
      this.adedShow = true
      //调用子组件的方法
      this.$refs.aded.setProp(type, pid)
    }
  },
  created () {
    this.getAllPermission()
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
  .box {
    text-align: right;
  }
}
</style>
